part of '../repository.dart';

const _kInbuiltCollectionFolderTypeValue = 'inbuilt_collection_folder';

class _InbuiltCollectionFolderDto extends Equatable
    implements _InbuiltCollectionListItemDto, _CollectionFolderDto {
  const _InbuiltCollectionFolderDto({
    required this.id,
    required this.titles,
    required this.collectionDtos,
  });

  @override
  final String id;

  @override
  final BuiltMap<String, String> titles;

  @override
  final BuiltList<_InbuiltCollectionDto> collectionDtos;

  @override
  String get type => _kInbuiltCollectionFolderTypeValue;

  @override
  List<Object?> get props {
    return [
      id,
      titles,
      collectionDtos,
    ];
  }

  factory _InbuiltCollectionFolderDto.fromJson(Map<String, dynamic> json) {
    final titleMap = json[_kInbuiltCollectionListItemTitlesKey] as Map;

    final titles = titleMap.map((languageCode, title) {
      return MapEntry(languageCode as String, title as String);
    }).build();

    final collectionMaps = List.castFrom<dynamic, Map>(json[_kCollectionFolderCollectionsKey]);

    final collectionDtos = collectionMaps.map((collectionMap) {
      final collectionJson = Map.castFrom<dynamic, dynamic, String, dynamic>(collectionMap);

      return _InbuiltCollectionDto.fromJson(collectionJson);
    }).toBuiltList();

    return _InbuiltCollectionFolderDto(
      id: json[_kCollectionListItemIdKey],
      titles: titles,
      collectionDtos: collectionDtos,
    );
  }

  factory _InbuiltCollectionFolderDto.fromEntity(InbuiltCollectionFolder folder) {
    final collectionDtos = folder.collections.map((collection) {
      return _InbuiltCollectionDto.fromEntity(collection);
    }).toBuiltList();

    return _InbuiltCollectionFolderDto(
      id: folder.id,
      titles: folder.titles,
      collectionDtos: collectionDtos,
    );
  }

  @override
  Map<String, dynamic> toJson() {
    final collectionJsons = collectionDtos.map((collectionDto) {
      return collectionDto.toJson();
    }).toList();

    return {
      _kCollectionListItemTypeKey: type,
      _kCollectionListItemIdKey: id,
      _kInbuiltCollectionListItemTitlesKey: titles.toMap(),
      _kCollectionFolderCollectionsKey: collectionJsons,
    };
  }

  @override
  InbuiltCollectionFolder toEntity() {
    final collections = collectionDtos.map((collectionDto) {
      return collectionDto.toEntity();
    }).toBuiltList();

    return InbuiltCollectionFolder(
      id: id,
      titles: titles,
      collections: collections,
    );
  }
}
